package com.meixiang.http;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.PostRequest;
import com.meixiang.R;
import com.meixiang.global.Config;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * author:xiejingwen
 * <p/>
 * <p/>
 * https://github.com/jeasonlzy0216/OkHttpUtils
 */
public class HttpUtils {
    private static Context mContext;
    public static boolean isAnalog = false;//是否虚拟数据
    public static Object tag;


    private HttpUtils() {

    }

    public static void init(Activity activity) {
        mContext = activity;
       setTag(activity);
    }

    public static void setTag(Object mTag){
        tag=mTag;
    }
    /*
     *post请求
     *
     * @param url      请求地址
     * @param params   参数
     * @param callBack 回调接口
     */
    public static void post(String url, HttpParams params, HttpCallBack callBack) {
        if (isAnalog) {
            getAssets(url, callBack);
        } else {

            if (null != params) {

                Log.e("params",params.toString());
            }
            OkHttpUtils.post(url)
                    .params(params)
                    .tag(tag)
                    .headers(getHeader())
                    .execute(callBack);
        }

    }
    /*
         *post请求
         *
         * @param url      请求地址
         * @param params   参
         * @param callBack 回调接口
         */
    public static void postr(String url, HttpParams params, HttpCallBack callBack) {
        if (isAnalog) {
            getAssets(url, callBack);
        } else {

            OkHttpUtils.post(url)
                    .params(params)
                    .tag(tag)
                    .headers(getHeader())
                    .execute(callBack);
        }
    }

    public static void post(String url, String callTag,  HttpParams params, HttpCallBack callBack) {
        if (isAnalog) {
            getAssets(url, callBack);
        } else {
            OkHttpUtils.post(url)
                    .params(params)
                    .tag(callTag)
                    .headers(getHeader())
                    .execute(callBack);
        }

    }

    public static void getC(String url, HttpCallBack callBack) {
        if (isAnalog) {
            getAssets(url, callBack);
        } else {
            OkHttpUtils.get(url)
                    .tag(tag)
                    .addCookie("SESSIONID",MXApplication.mApp.getSession().get("fundSessionId"))
                    .execute(callBack);
        }

    }


    /*
     * get请求
     * @param url      请求地址
     * @param callBack 回调接口
     */
    public static void get(String url, HttpCallBack callBack) {
        if (isAnalog) {
            getAssets(url, callBack);
        } else {
            OkHttpUtils.get(url).tag(tag).headers(getHeader()).execute(callBack);
        }

    }

    /*
      * 上传文件  回调接口中复写 inProgress(float progress) 查看进度
      * @param url   上传路径
      * @param name  上传文件的key
      * @param fileName  文件的名字
      * @param file      上传的文件
      * @param callback  回调
      */
    public static void postFile(String url, String name, String fileName, File file, StringCallback callback) {
        OkHttpUtils.post(url).headers(getHeader()).params(name, file, fileName).execute(callback);

    }

    /**
     * 上传文件  回调接口中复写 inProgress(float progress) 查看进度
     *
     * @param url      上传路径
     * @param params   参数
     * @param callBack 回调
     */
    public static void postFile(String url, HttpParams params, HttpCallBack callBack) {
        PostRequest postRequest = OkHttpUtils.post(url);
        //解决无法只上传文字的问题
        if (params.fileParamsMap == null || params.fileParamsMap.size() == 0) {
            File file = getFile(R.mipmap.app_logo,Config.base_data_path+Config.FILE_NAME);
            if (file != null) {
                params.put("Images", file);
            }
        }
        postRequest.headers(getHeader()).params(params).tag(tag).execute(callBack);

    }


    /**
     * 多文件上传
     *
     * @param url      上传路径
     * @param params   参数
     * @param key      图片key
     * @param files    文件集合
     * @param callBack 回调
     */
    public static void postFiles(String url, HttpParams params, String key, List<File> files, HttpCallBack callBack) {
        if (params == null) {
            params = new HttpParams();
        }
        params.putFileParams(key, files);
        postFile(url, params, callBack);
    }

    private static File getFile(int resId, String pathName) {
        Resources r = mContext.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(r, resId);
        File extDir = Environment.getExternalStorageDirectory();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File f = new File(extDir, pathName);
            FileOutputStream fOut = null;
            if (!f.exists()) {
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                fOut = new FileOutputStream(f);
                bmp.compress(Bitmap.CompressFormat.PNG, 1, fOut);
                fOut.flush();
                fOut.close();
                return f;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return f;
        } else {
            AbToastUtil.showToast(mContext, "没有内存卡");
        }
        return null;
    }

    /*
     * 文件下载  new FileCallBack 需传入保存的路径与文件名
     * @param url
     * @param callBack   可监听下载进度，是否下载成功
     */
    public static void DownLoadFile(String url, FileCallback callBack) {
        OkHttpUtils.get(url).headers(getHeader()).execute(callBack);
    }

    /*
     * 根据tag取消请求 BaseActivity的onDestroy()中进行调用
     * @param tag
     */
    public static void tagCancelRequest(Object tag) {
        OkHttpUtils.getInstance().cancelTag(tag);
    }


    /*
     * 请求头信息
     * @return
     */
    public static HttpHeaders getHeader() {
        HttpHeaders headers = new HttpHeaders();
        if (!Tool.isBlank(MXApplication.mApp.getSession().get("jsessionid")))
            headers.put("jsessionid", MXApplication.mApp.getSession().get("jsessionid"));
        if (!Tool.isBlank(MXApplication.mApp.getSession().get("fundSessionId")))
            headers.put("fundSessionId", MXApplication.mApp.getSession().get("fundSessionId"));
//        headers.put("deviceId", Tool.getAppId(mContext));
//        headers.put("Request-From", "AndroidApp");
//        headers.put("randomCode", Tool.getCharAndNumr(10));
        return headers;
    }

    /**
     * 获取虚拟数据
     *
     * @param url
     * @param callBack
     */
    private static void getAssets(String url, HttpCallBack callBack) {
        Log.e("url", url);
        String[] urls = url.split("/");
        for (int i = 0; i < urls.length; i++) {
            Log.e("urls", urls[i]);
        }
        AssetManager assetManager = mContext.getAssets();
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            if (url.contains("/api")) {
                is = assetManager.open(urls[urls.length - 3] + "/" + urls[urls.length - 1] + ".json");
            } else {
                is = assetManager.open(urls[urls.length - 2] + "/" + urls[urls.length - 1] + ".json");
            }
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            StringBuffer stringBuffer = new StringBuffer();
            String str = null;
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            String response = stringBuffer.toString();
            if (AbStrUtil.isEmpty(response)) {
                AbToastUtil.showToast(mContext, "获取失败，请检查assets文件夹或文件名是否正确");
            } else {
                Log.e("response", response);
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.optString("code").equals("0")) {
                    callBack.onSucceed(jsonObject.optJSONObject("result"), jsonObject.optString("code"), jsonObject.optString("message"));
                } else {
                    callBack.onError(jsonObject.optString("code"), jsonObject.optString("message"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //return  null;
    }

}
